<?php

namespace app\api\controller;

use app\api\model\Category as CategoryModel;
use app\api\model\WxappCategory as WxappCategoryModel;
use app\api\model\Goods as GoodsModel;
use think\Db;
/**
 * 商品分类控制器
 * Class Goods
 * @package app\api\controller
 */
class Category extends Controller
{
    /**
     * 分类页面
     * @return array
     * @throws \think\exception\DbException
     */
    public function index()
    {
        // 分类模板
        $templet = WxappCategoryModel::detail();
        // 商品分类列表
        $list = array_values(CategoryModel::getCacheTree());
        return $this->renderSuccess(compact('templet', 'list'));
    }
    /**
     * undocumented function summary
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function sousuozt()
    {
        $keyword = input('key'); // 获取关键词
        $domain = request()->domain();
    
        $domain = request()->domain(); // 当前域名，如 http://mx.zaoyiwang.com

        $list = Db('category')
            ->alias('c')
            ->join('upload_file f1', 'c.image_id = f1.file_id', 'LEFT')
            ->join('upload_file f2', 'c.img = f2.file_id', 'LEFT')
            ->where('c.name', 'like', "%{$keyword}%")
            ->where('c.is_zt_show', 1)
            ->order('c.sort asc')
            ->field([
                'c.*',
                "CONCAT('$domain/uploads/', f1.file_name) as image_url",
                "CONCAT('$domain/uploads/', f2.file_name) as img_url"
            ])
            ->select();
    
        return [
            'code' => 1,
            'msg' => 'success',
            'data' => [
                'templet' => [
                    'category_style' => 20,
                    'share_title' => '',
                ],
                'list' => $list,
            ]
        ];
    }
    /**
     * undocumented function summary
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function info()
    {
        $category_id = input('category_id/d', 0);
        $domain = request()->domain(); // 当前域名
    
        // 模板详情，带 image 和 ztImage
        $model = CategoryModel::get($category_id, ['image', 'ztImage']);
        $in_category_id = DB("category")
            ->where('parent_id', $category_id)
            ->column('category_id');
        $in_category_id[] = $category_id; // 包括自身
        // 获取医生列表，关联职称和图片
        $list = Db::name('goods')
            ->alias('g')
            ->join('goods_sku gs', 'g.goods_id = gs.goods_id', 'LEFT')
            ->join('goods_image gi', 'g.goods_id = gi.goods_id', 'LEFT')
            ->join('upload_file uf', 'gi.image_id = uf.file_id', 'LEFT')
            ->where('g.is_delete', 0)
            ->where('g.category_id','in' ,$in_category_id)
            ->field([
                'g.goods_id',
                'g.goods_name',
                'g.category_id',
                'gs.goods_no', // 职称
                'uf.file_name',
                'g.sales_initial',
                'g.selling_point',
            ])
            ->select()->toArray();
        // 拼接图片完整路径
        foreach ($list as &$item) {
            $item['image_url'] = $item['file_name'] ? $domain . '/uploads/' . $item['file_name'] : '';
            unset($item['file_name']); // 如果不需要保留原始字段可以移除
        }
    
        return $this->renderSuccess(compact('model', 'list'));
    }
    public function sousuo()
    {
        $keyword = input('key'); // 获取用户输入的关键字
        $result = [];
    
        // ========== 1. 优先查找医生 ==========
        if (!empty($keyword)) {
            $matchedDoctors = DB('goods')
                ->where('goods_name', 'like', "%$keyword%")
                ->where('goods_status', 10)
                ->where('is_delete', 0)
                ->select();
        
            if ($matchedDoctors && count($matchedDoctors) > 0) {  // ✅ 更严格判断
                // 将医生按二级科室 category_id 分组
                $groupedDoctors = [];
                foreach ($matchedDoctors as $doctor) {
                    $groupedDoctors[$doctor['category_id']][] = $doctor;
                }
        
                // 获取这些二级科室
                $secondCategories = DB('category')
                    ->whereIn('category_id', array_keys($groupedDoctors))
                    ->where('is_show', '1')
                    ->select();
        
                foreach ($secondCategories as $secondCategory) {
                    $firstCategory = DB('category')
                        ->where('category_id', $secondCategory['parent_id'])
                        ->where('is_show', '1')
                        ->find();
        
                    if (!$firstCategory) continue;
        
                    $result[] = [
                        'category_id' => $firstCategory['category_id'],
                        'name' => $firstCategory['name'],
                        'parent_id' => $firstCategory['parent_id'],
                        'image_id' => $firstCategory['image_id'],
                        'sort' => $firstCategory['sort'],
                        'wxapp_id' => $firstCategory['wxapp_id'],
                        'create_time' => $firstCategory['create_time'],
                        'update_time' => $firstCategory['update_time'],
                        'child' => $groupedDoctors[$secondCategory['category_id']],
                    ];
                }
        
                if (!empty($result)) {
                    return [
                        'code' => 1,
                        'msg'  => 'success',
                        'data' => [
                            'templet' => [
                                'category_style' => 20,
                                'share_title' => '',
                            ],
                            'list' => $result,
                        ]
                    ];
                }
            }
        }
    
        // ========== 2. 若未命中医生，再查科室（一级 + 二级） ==========
        if (!empty($keyword)) {
            // 查一级科室
            $firstLevelCategories = DB('category')
                ->where('parent_id', 0)
                ->where('is_doctor', 1)
                ->where('name', 'like', "%$keyword%")
                ->where('is_show', '1')
                ->order("sort asc")
                ->select();
    
            if (!empty($firstLevelCategories)) {
                foreach ($firstLevelCategories as $firstCategory) {
                    $secondLevelCategories = DB('category')
                        ->where('is_doctor', 1)
                        ->where('parent_id', $firstCategory['category_id'])
                        ->where('is_show', '1')
                        ->order("sort asc")
                        ->select();
    
                    $result[] = [
                        'category_id' => $firstCategory['category_id'],
                        'name' => $firstCategory['name'],
                        'parent_id' => $firstCategory['parent_id'],
                        'image_id' => $firstCategory['image_id'],
                        'sort' => $firstCategory['sort'],
                        'wxapp_id' => $firstCategory['wxapp_id'],
                        'create_time' => $firstCategory['create_time'],
                        'update_time' => $firstCategory['update_time'],
                        'child' => $secondLevelCategories,
                    ];
                }
            } else {
                // 查二级科室
                $secondLevelCategories = DB('category')
                    ->where('is_doctor', 1)
                    ->where('parent_id', '>', 0)
                    ->where('name', 'like', "%$keyword%")
                    ->where('is_show', '1')
                    ->order("sort asc")
                    ->select();
    
                foreach ($secondLevelCategories as $secondCategory) {
                    $firstCategory = DB('category')
                        ->where('is_doctor', 1)
                        ->where('category_id', $secondCategory['parent_id'])
                        ->where('is_show', '1')
                        ->find();
    
                    if (!$firstCategory) continue;
    
                    $result[] = [
                        'category_id' => $firstCategory['category_id'],
                        'name' => $firstCategory['name'],
                        'parent_id' => $firstCategory['parent_id'],
                        'image_id' => $firstCategory['image_id'],
                        'sort' => $firstCategory['sort'],
                        'wxapp_id' => $firstCategory['wxapp_id'],
                        'create_time' => $firstCategory['create_time'],
                        'update_time' => $firstCategory['update_time'],
                        'child' => [$secondCategory],
                    ];
                }
            }
        }
    
        // ========== 3. 关键词为空：默认显示全部 ==========
        if (empty($keyword)) {
            $firstLevelCategories = DB('category')
                ->where('is_doctor', 1)
                ->where('parent_id', 0)
                ->where('is_show', '1')
                ->order("sort asc")
                ->select();
    
            foreach ($firstLevelCategories as $firstCategory) {
                $secondLevelCategories = DB('category')
                    ->where('is_doctor', 1)
                    ->where('parent_id', $firstCategory['category_id'])
                    ->where('is_show', '1')
                    ->order("sort asc")
                    ->select();
    
                $result[] = [
                    'category_id' => $firstCategory['category_id'],
                    'name' => $firstCategory['name'],
                    'parent_id' => $firstCategory['parent_id'],
                    'image_id' => $firstCategory['image_id'],
                    'sort' => $firstCategory['sort'],
                    'wxapp_id' => $firstCategory['wxapp_id'],
                    'create_time' => $firstCategory['create_time'],
                    'update_time' => $firstCategory['update_time'],
                    'child' => $secondLevelCategories,
                ];
            }
        }
    
        // ========== 返回最终数据结构 ==========
        return [
            'code' => 1,
            'msg'  => 'success',
            'data' => [
                'templet' => [
                    'category_style' => 20,
                    'share_title' => '',
                ],
                'list' => $result,
            ]
        ];
    }
}
